package tree;

import haxe.rtti.Rtti;
import h3d.prim.Disc;
import haxe.ds.GenericStack;
import haxe.ds.HashMap;

//枝条节点
class Tress extends Leaf{
    private var m_leafMap : Map<LeafKind, Leaf>;
    private var m_stack : GenericStack<LeafKind>;
    //只更新一个节点
    private var m_isSingleLeafUpdate : Bool = true;
    
    public function new() {
        super();
        m_leafMap = [];
        m_stack = new GenericStack<LeafKind>();
    }
    

    public override function OnUpdate(msg:LeafMsg) {
        super.OnUpdate(msg);
        if(m_isSingleLeafUpdate){
            var first = m_stack.first();
            if(first != null){
                m_leafMap[first].OnUpdate(msg);
            }
        }
        else {
            var values = m_stack.iterator();
            for (value in values){
                m_leafMap[value].OnUpdate(msg);
            }
        }
    }

    //增加叶结点
    public function AddLeaf(kind:LeafKind, leaf:Leaf){
        leaf.SetParent(this);
        m_leafMap[kind] = leaf;
    }
    //移除叶结点
    public function RemoveLeaf(kind:LeafKind) {
        m_leafMap.remove(kind);
    }
    
    //获取叶结点
    public function GetLeaf(kind:LeafKind) {
        var leaf = m_leafMap[kind];
        return leaf;
    }
    //通过地址获取叶结点
    public function GetLeafByPath(kinds:Array<LeafKind>)  {
        var len = kinds.length;
        var head : Tress = this;
        var res : Leaf = null;
        for (i in 0 ...len){
            if(i == len - 1){
                res = head.GetLeaf(kinds[i]);
            }
            else {
                head = cast head.GetLeaf(kinds[i]);
            }
        }
        return res;
    }


    //将一个叶结点放入运行栈
    public function PushLeaf(kind:LeafKind) {
        var last = m_stack.first();
        m_stack.add(kind);
        m_leafMap[kind].OnEnter(last);
    }

    //弹出运行栈的第一个节点
    public function PopLeaf() {
        var kind = m_stack.pop();
        var next = m_stack.first();
        m_leafMap[kind].OnExit(next);
    }

}
